<template>
  <el-tree-select v-if="showTree"
                  class="myTree"
                  ref="treeSelect"
                  :value="value"
                  popover-class="test-class-wrap"
                  value-key="id"
                  :select-params="selectParams"
                  :tree-params="treeParams"
                  :filter-node-method="_filterFun"
                  @searchFun="_searchFun"
                  @removeTag="harmfactorChangeRemove"
                  @check="harmfactorChange"
                  @select-clear="clearHarm"
  />
</template>

<script>
export default {
  name: 'my-tree-select',
  props: {
    children: { default: 'children' },
    label: { default: 'label' },
    valueField: { default: 'id' },
    value: { default: ()=>[] },
    data: { default: ()=>[] },
  },
  data() {
    return {
      showTree: true,
      selectParams: {
        clearable: true,
        placeholder: '请选择危害',
        multiple: true
      },
      treeParams: {
        clickParent: true,
        filterable: true,
        // 只想要子节点，不需要父节点
        leafOnly: true,
        showCheckbox: true,
        includeHalfChecked: false,
        'check-strictly': false,
        'default-expand-all': true,
        'expand-on-click-node': false,
        data: this.data,
        props: {
          children: this.children,
          label: this.label,
          rootId: '0',
          disabled: 'disabled',
          parentId: 'pid',
          value: this.valueField
        }
      },
    }
  },
  watch: {
    data() {
      this.treeParams.data = this.data
      this.showTree = false
      this.$nextTick(()=>{
        this.showTree = true
      })
    },
  },
  methods:{
    _filterFun(value, data, node) {
      if (!value) return true
      return data[this.label].indexOf(value) !== -1
    },
    // 树过滤
    _searchFun(value) {
      // 自行判断 是走后台查询，还是前端过滤
      this.$refs.treeSelect.filterFun(value)
    },
    harmfactorChangeRemove(data, node) {
      data.forEach(item=>{
        const index = this.value.indexOf(item);

        if (index > -1) {
          this.value.splice(index, 1);
        }
      })

      this.$emit('input', this.value)
    },
    clearHarm(){
      this.$emit('input', [])
    },
    harmfactorChange(data, node) {
      this.$emit('input', node.checkedKeys)
      this.$emit('change', node.checkedNodes, node.checkedKeys)
      //this.form.touchHarms = this.getHarmLabel(node.checkedKeys).map((t) => { return t.hamName }).join(',')
    },
  }
}
</script>

<style scoped>
.myTree ::v-deep .el-select{
  width: 100%;
}
</style>
